<template>
  <div class="bk">
    <h1 class="t1">防 反 贫 数 字 化 监 测 平 台</h1>
    <!-- 添加外层容器使卡片居中 -->
    <form class="register-container">
      <el-card class="register-card">
        <!-- 顶部 -->
        <template #header>
          <h1 style="text-align: center;">注 册</h1>
        </template>

        <!-- 表单区域 - 添加 rules 绑定和 ref -->
        <el-form
          ref="registerFormRef"
          label-width="70px"
          class="register-form"
          :model="registerForm"
          :rules="rules"
        >
          <!-- 用户名输入框 - 添加 prop -->
          <el-form-item label="用 &nbsp户&nbsp名" prop="username">
            <el-input
              type="text"
              v-model="registerForm.username"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>

          <!-- 用户姓名输入框 - 添加 prop -->
          <el-form-item label="用户姓名" prop="userRealname">
            <el-input
              type="text"
              v-model="registerForm.userRealname"
              placeholder="请输入用户姓名"
            ></el-input>
          </el-form-item>

           <!-- 身份证号 -->
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              type="text"
              v-model="registerForm.idCard"
              placeholder="请输入身份证号"
            ></el-input>
          </el-form-item>

            <!-- 用户性别 -->
          <el-form-item label="用户性别" prop="gender">
            <el-radio-group v-model="registerForm.gender">
              <el-radio label="M">男</el-radio>
              <el-radio label="F">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 账号 - 添加 prop -->
          <el-form-item label="电 &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp话" prop="account">
            <el-input
              type="text"
              v-model="registerForm.account"
              placeholder="请输入联系电话"
            ></el-input>
          </el-form-item>
          
          <!-- 密码输入框 - 添加 prop -->
          <el-form-item label="密&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp码" prop="password">
            <el-input
              type="password"
              v-model="registerForm.password"
              placeholder="请输入密码"
              show-password
            ></el-input>
          </el-form-item>

          <!-- 确认密码 - 添加 prop -->
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              type="password"
              v-model="registerForm.confirmPassword"
              placeholder="请再次输入密码"
              show-password
            ></el-input>
          </el-form-item>

          <!-- 选择身份 - 添加 prop -->
          <el-form-item label="选择身份" prop="role">
            <el-select
              v-model="registerForm.role"
              placeholder="请选择身份"
            >
              <el-option label="用户" value="贫困户" />
              <el-option label="乡村干部" value="乡村干部" />
              <el-option label="市县干部" value="市县干部" />
              <el-option label="省级干部" value="省级干部" />
              <el-option label="管理员" value="管理员" />
            </el-select>
          </el-form-item>

          </el-form>



        <!-- 底部登录按钮 -->
        <template #footer>
          <div style="text-align: center;" class="ov">
            <el-button 
              type="primary" 
              @click.prevent="handleSubmit" 
              size="large"
              :loading="loading"
            >
              确认
            </el-button>
            <el-button type="primary" @click.prevent="handleCancel" size="large">取消</el-button>
          </div>
        </template>
      </el-card>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {RegisterAPI} from '@/api/register';

const router = useRouter();
const registerFormRef = ref();
const loading = ref(false);

// 注册表单数据
let registerForm = reactive({
  username: '',
  userRealname: '',
  account: '',
  password: '',
  confirmPassword: '', // 修改为 confirmPassword 以匹配验证规则
  role: '',
  gender: '', // 新增：用户性别
  idCard: ''  // 新增：身份证号
});

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
  ],
  userRealname: [
    { required: true, message: '请输入用户姓名', trigger: 'blur' }
  ],
  account: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  role: [
    { required: true, message: '请选择身份', trigger: 'change' }
  ],
  gender: [ // 新增：性别验证规则
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  idCard: [ // 新增：身份证号验证规则
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        // 简单的身份证号验证（18位，最后一位可以是X）
        const idCardRegex = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (!idCardRegex.test(value)) {
          callback(new Error('请输入有效的身份证号'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 处理表单提交
const handleSubmit = async () => {
  try {
    // 1. 验证表单
    const isValid = await validateForm();
    
    if (!isValid) {
      ElMessage.warning('请填写正确的注册信息');
      return;
    }
    
    loading.value = true;
    
    // 2. 模拟注册请求（实际项目中替换为真实API调用）
    //await new Promise(resolve => setTimeout(resolve, 1000));
    RegisterAPI(registerForm).then(res=>{
      // console.register(res)
      if(res.code==2000){
        router.push("/login")
      }
      else{
        ElMessage.error("注册失败")
      }
    }).catch(err=>{});
    
  } catch (error) {
    console.error('注册失败:', error);
    ElMessage.error('注册失败，请检查输入信息');
  } finally {
    loading.value = false;
  }
};

// 表单验证方法
const validateForm = async () => {
  try {
    await registerFormRef.value.validate();
    return true;
  } catch (error) {
    return false;
  }
};

// 取消按钮处理
const handleCancel = () => {
  router.go(-1);
};
</script>

<style lang="less" scoped>
.bk {
  /* 背景图设置 */
  background-image: url("@/assets/background.jpg");
  background-size: cover;       /* 覆盖整个容器 */
  background-position: center;  /* 居中显示 */
  background-repeat: no-repeat; /* 不重复 */
  background-attachment: fixed; 
  
  /* 确保元素填满整个视口 */
  position: fixed;             /* 固定定位，防止滚动 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  
  /* 移除默认边距 */
  margin: 0;
  padding: 0;
  
  /* 可选：防止内容溢出 */
  overflow: hidden;
}

.t1 {
  margin-top: 90px;
  font-size: 60px;
  text-align: center;
}

.register-container {
  display: flex;
  justify-content: center;
  margin-top: 80px;
  height: 65vh;
  width: 100%;
}

.register-card {
  align-items: center;
  width: 520px; /* 卡片宽度 */
  border-radius: 15px; /* 圆角 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 阴影 */
  background-color: rgba(255, 255, 255, 0.5);
  text-align: center;
}

.register-form {
  padding: 20px 30px;

  .el-form-item {
    margin-bottom: 22px;
  }
}
</style>
